package com.example.service;

import com.example.entity.SysUser;
import com.example.repository.SysUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.MessageDigest;
import java.util.Optional;

@Service
public class AuthService {

    @Autowired
    private SysUserRepository sysUserRepository;
    
    public SysUser authenticate(String username, String password, String roleId) throws Exception {
        // 根据工号或手机号查找用户
        Optional<SysUser> userOpt;
        
        if (username.matches("^\\d+$")) {
            // 如果输入的全是数字，认为是手机号
            userOpt = sysUserRepository.findByPhone(username);
        } else {
            // 否则认为是工号
            userOpt = sysUserRepository.findByJobNumber(username);
        }
        
        if (userOpt.isEmpty()) {
            throw new Exception("用户不存在");
        }
        
        SysUser user = userOpt.get();
        
        // 验证密码（MD5加密后比较）
        String md5Password = getMD5String(password);
        if (!user.getPassword().equals(md5Password)) {
            throw new Exception("密码错误");
        }
        
        // 验证角色
        if (!user.getRoleId().toString().equals(roleId)) {
            throw new Exception("您没有权限以该角色登录");
        }
        
        // 检查用户状态
        if (!"正常".equals(user.getStatus())) {
            throw new Exception("账号已被禁用");
        }
        
        return user;
    }
    
    // MD5加密方法
    private String getMD5String(String str) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] bytes = md.digest(str.getBytes());
            StringBuilder sb = new StringBuilder();
            for (byte b : bytes) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
}